package lesson.user;
import lesson.db.DbUtil;
import lesson.until.Md5Until;
import org.apache.ibatis.session.SqlSession;

import java.util.Objects;

public class UserService {


    /**
     * 添加用户
     * @param user
     */
    public String addUser(User user) {
        if (user.getName() == null || user.getName().trim().equals("")) {
            return "请填写用户名";
        }
        if (user.getPwd() == null || user.getPwd().trim().equals("")) {
            return "请填写密码";
        }

        if (user.getRole() == null || user.getRole()<1 || user.getRole() > 3) {
            return "请选择角色";
        }

        if (checkExist(user.getName())) {
            return "该名称已被注册";
        }


        user.setPwd(Md5Until.cal(user.getPwd()));



        SqlSession session = DbUtil.getSession(true);
        UserDao userDao = session.getMapper(UserDao.class);
        userDao.addUser(user);
        session.close();

        return null;

    }


    /**
     * 检测叫这个名字的用户是否存在
     * @param name
     * @return
     */
    public boolean checkExist(String name) {
        SqlSession session = DbUtil.getSession(true);
        UserDao userDao = session.getMapper(UserDao.class);
        boolean exist = userDao.checkExist(name);
        session.close();
        return exist;
    }

    /**
     * 根据名字获取用户
     * @param name
     * @return
     */
    public User getByName(String name) {


        SqlSession session = DbUtil.getSession(true);
        UserDao userDao = session.getMapper(UserDao.class);
        User user = userDao.getByName(name);
        session.close();
        return user;
    }

    /**
     * 登录检测，信息完全匹配，就返回对应的用户，否则返回null
     * @param name
     * @param pwd
     * @param role
     * @return
     */
    public User checkLogin(String name, String pwd, Integer role) {
        if (name == null || name.trim().equals("")) {
            return null;
        }
        if (pwd == null || pwd.trim().equals("")) {
            return null;
        }

        if (role == null || role<1 || role > 3) {
            return null;
        }

        User dbItem = getByName(name);
        if (dbItem == null) {
            return null;
        }
        if (Objects.equals(dbItem.getPwd(), Md5Until.cal(pwd)) == false || Objects.equals(dbItem.getRole(), role) == false) {
            return null;
        }

        return dbItem;

    }


}
